import { login } from './url'
import type { App } from 'vue'
import request from './axios.config'
import { Message, Modal } from '@arco-design/web-vue'
import useUserStore from '@/store/modules/user'
import qs from 'qs'
import router from '@/router'
export interface HttpOption {
  url: string
  data?: any
  method?: string
  headers?: any
  beforeRequest?: () => void
  afterRequest?: () => void
}

export interface Response<T = any> {
  blob(): unknown
  [x: string]: any
  totalSize: number | 0
  code: number
  msg: string
  data: T
}

function IsPC() {
  const userAgentInfo = navigator.userAgent
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
  let flag = true
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false
      break
    }
  }
  return flag
}

function http({ url, data, method, headers, beforeRequest, afterRequest }: HttpOption) {
  const successHandler = (res: any) => {
    if (res.config.url?.indexOf('export') > 0 || res.config.url?.indexOf('download') > 0) {
      return res
    } else {
      if (res.data.code === 0) {
        return res.data
      } else {
        Message.success(res.data.msg)
      }
    }
  }
  const failHandler = (error: Response<Error>) => {
    // if (error.msg == '请先登陆') {
    //   router.push('/login')
    //   location.reload()
    // }
    afterRequest && afterRequest()
    const userStore = useUserStore()
    if (error.code === 14) {
      if (window.location.pathname.split('/')[1] == 'children') {
        // router.push('/children/login')
        // // window.location.reload()
        router
          .replace({
            path: '/children/login',
          })
          .then(() => {
            window.location.reload()
          })
      } else {
        userStore.logout().then(() => {
          localStorage.clear()
          window.location.reload()
        })
      }
      // userStore.logout().then(() => {
      //   localStorage.clear()
      //   window.location.reload()
      // })
      // window.location.reload()
      Message.error(error.msg || '请求失败，未知异常')
    } else {
      if (IsPC() == false && url == '/app/admin/login') {
        Modal.info({
          content: error.msg,
        })
      } else if (IsPC() == false && url == '/app/user/login') {
        Modal.info({
          content: error.msg,
        })
      } else {
        Message.error(error.msg || '请求失败，未知异常')
      }

      // userStore.logout().then(() => {
      //   window.location.reload()
      // })
    }
    // return error
  }
  beforeRequest && beforeRequest()
  method = method || 'GET'
  const params = Object.assign(typeof data === 'function' ? data() : data || {}, {})

  const params1 = '?' + qs.stringify(params, { arrayFormat: 'repeat' })
  return method === 'GET'
    ? request.get(url + params1, { headers }).then(successHandler, failHandler)
    : request.post(url, params, { headers: headers }).then(successHandler, failHandler)
}

export function get({
  url,
  data,
  method = 'GET',
  beforeRequest,
  afterRequest,
}: HttpOption): Promise<Response> {
  return http({
    url,
    method,
    data,
    beforeRequest,
    afterRequest,
  })
}

export function formpost({
  url,
  data,
  method = 'POST',
  beforeRequest,
  afterRequest,
}: HttpOption): Promise<Response> {
  return http({
    url,
    method,
    data,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    },
    beforeRequest,
    afterRequest,
  })
}
export function post({
  url,
  data,
  method = 'POST',
  beforeRequest,
  afterRequest,
}: HttpOption): Promise<Response> {
  return http({
    url,
    method,
    data,
    beforeRequest,
    afterRequest,
  })
}

function install(app: App): void {
  app.config.globalProperties.$http = http

  app.config.globalProperties.$get = get

  app.config.globalProperties.$post = post
}

export default {
  install,
  get,
  post,
}

declare module '@vue/runtime-core' {
  // 为 `this.$` 提供类型声明
  interface ComponentCustomProperties {
    $get: <T>(options: HttpOption) => Promise<Response<T>>
    $post: <T>(options: HttpOption) => Promise<Response<T>>
  }
}
